package com.neusoft.neumooc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neusoft.core.common.BaseController;
import com.neusoft.core.common.conf.Params;
import com.neusoft.neumooc.service.ParamService;
import com.neusoft.neumooc.vo.ParamVO;

@Controller
@RequestMapping(value = "/param")
public class ParamController extends BaseController {

    @Autowired
    private ParamService paramService;

    /**
     * 跳转到基本信息页面
     */
    @RequestMapping(value = "/param")
    public String param(Model model) {
        try {
            log.info("开始获取参数列表...");
            List<ParamVO> params = paramService.getAllParams();
            log.info("获取到的参数列表: " + params);
            if (params != null && !params.isEmpty()) {
                for (ParamVO param : params) {
                    log.info("参数: id=" + param.getParamId() + 
                            ", name=" + param.getParamName() + 
                            ", value=" + param.getParamValue());
                }
            } else {
                log.warn("未获取到任何参数数据");
            }
            model.addAttribute("params", params);
        } catch (Exception e) {
            log.error("获取参数列表失败", e);
        }
        return "param/param";
    }

    /**
     * 更新参数
     */
    @ResponseBody
    @RequestMapping(value = "/updateParam")
    public Map<String, Object> updateParam(HttpServletRequest request) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            String[] paramIds = request.getParameter("paramIds").split(",");
            String[] paramValues = request.getParameter("paramValues").split(",");
            
            List<ParamVO> params = new ArrayList<ParamVO>();
            for(int i = 0; i < paramIds.length; i++) {
                ParamVO param = new ParamVO();
                param.setParamId(paramIds[i]);
                param.setParamValue(paramValues[i]);
                params.add(param);
            }
            
            boolean result = paramService.updateParams(params);
            if(result) {
                retMap.put(Params.RET_CODE, Params.RET_CODE_SUCCESS);
                retMap.put(Params.RET_OBJ, "保存成功");
            } else {
                retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
                retMap.put(Params.RET_OBJ, "保存失败");
            }
        } catch (Exception e) {
            log.error("更新参数失败", e);
            retMap.put(Params.RET_CODE, Params.RET_CODE_ERROR);
            retMap.put(Params.RET_OBJ, "更新参数失败");
        }
        return retMap;
    }
} 